#! /usr/bin/env python
#coding=utf-8
"""
views
"""

import base64
import time
import datetime

from flask import Module, Response, request, flash, jsonify, g, current_app,\
    abort, redirect, url_for, session, Blueprint, render_template

from flask.ext.principal import identity_changed, Identity, AnonymousIdentity

from planet.account import backend, frontend
from planet.account.forms import LoginForm, RegisterForm, UserForm, ProfileForm
from planet.account.models import User, Profile
from planet.extensions import db, cache
from planet.permissions import auth, operator, admin
from planet.account.api import requires_auth


@backend.route("/login/", methods=["GET", "POST"])
def login():
    form = LoginForm(account=request.args.get('account', None),
                     next=request.args.get('next', None))

    if form.validate_on_submit():
        user, authenticated = User.query.authenticate(form.account.data,
                                                      form.password.data)
        if user and authenticated:
            session.permanent = form.remember.data
            identity_changed.send(current_app._get_current_object(),
                                  identity=Identity(user.id))
            flash(u"Welcome back, %s" % user.username, "success")

            next_url = form.next.data

            if not next_url or next_url == request.path:
                # next_url = url_for('frontend.profile', username=user.username)
                next_url = url_for('backstage_backend.index')
            return redirect(next_url)

        else:

            flash(u"Sorry, invalid login", "error")

    return render_template("account/login.html", form=form)


@backend.route("/logout/")
def logout():
    flash(u"您已成功退出", "success")
    identity_changed.send(current_app._get_current_object(),
                          identity=AnonymousIdentity())

    next_url = request.args.get('next', '')

    if not next_url or next_url == request.path:
        next_url = url_for('backstage_backend.index')

    return redirect(next_url)


@backend.route("/register/", methods=["GET", "POST"])
def register():
    form = RegisterForm(next=request.args.get('next', None))
    if form.validate_on_submit():
        user = User(
                    last_login_ip=request.remote_addr,
                    current_login_ip=request.remote_addr
                    )
        form.populate_obj(user)
        db.session.add(user)
        db.session.commit()

        url = url_for('account_backend.activate', code=user.code, _external=True)

        send_email('激活您的帐号',
                    current_app.config['DEFAULT_MAIL_SENDER'],
                    [user.email],
                    render_template("account/register_mail.txt",url=url),
                    render_template("account/register_mail.html",url=url)
                    )

        flash(u"%s 注册成功, 请到你的邮箱激活账户。" % user.username, "success")

        next_url = form.next.data

        if not next_url or next_url == request.path:
            next_url = url_for('home_frontend.index')

        return redirect(next_url)

    return render_template("account/register.html", form=form)


@backend.route("/account", methods=["GET", "POST"])
@admin.require(403)
def index():
    page = int(request.args.get('p', 1))
    page_obj = User.query.order_by('-id').paginate(page, per_page=50)
    return render_template("account/index.html", page_obj=page_obj)


@backend.route("/account/new", methods=["GET", "POST"])
@admin.require(403)
def new():
    form = RegisterForm(next=request.args.get('next',None))
    if form.validate_on_submit():
        user = User(
            last_login_ip=request.remote_addr, 
            current_login_ip=request.remote_addr,
            active = True
            )
        form.populate_obj(user)
        db.session.add(user)
        db.session.commit()

        next_url = form.next.data

        if not next_url or next_url == request.path:
            next_url = url_for('account_backend.index')

        return redirect(next_url)

    return render_template("account/register.html", form=form)

@backend.route("/account/<int:id>/edit", methods=['GET','POST'])
@admin.require(403)
def edit(id):
    user = User.query.get_or_404(id)
    form = UserForm(
        user_id = user.id,
        username=user.username, 
        email=user.email, 
        role=user.role,
        active=user.active)
    if form.validate_on_submit():
        if user.id == 1:
            form.role.data = 1
        form.populate_obj(user)
        if user.active:
            user.code = ''

        db.session.add(user)
        db.session.commit()
        flash("Edit account success", "success")
        next_url = url_for('account_backend.edit',id=user.id)
        return redirect(next_url)
    return render_template("account/edit.html", form=form, user=user)


@backend.route("/account/<int:id>/send_active_mail")
@admin.require(403)
def account_active_mail(id):
    user = User.query.get_or_404(id)
    url = url_for('account.activate', code=user.code, _external=True)

    send_email('激活您的帐号-iGame.im',
                        current_app.config['DEFAULT_MAIL_SENDER'], 
                        [user.email],
                        render_template("account/register_mail.txt",url=url),
                        render_template("account/register_mail.html",url=url)
                        )

    flash("Send active email success", "success")
    next_url = url_for('account_backend.edit',id=user.id)
    return redirect(next_url)


@frontend.route("/costaclub/", methods=["GET","POST"])
def setting_profile():
    auth = request.authorization
    auth_str = request.values.get('auth')
    if not auth:
        if auth_str:
            auth_str = base64.decodestring(auth_str)
            class Auth():
                username = ''
                password = ''
            auth = Auth()
            auth.username = auth_str.split(':')[0]
            auth.password = auth_str.split(':')[1]
    user = None
    if auth:
        user, authenticated = User.query.authenticate(auth.username, auth.password)
        if not authenticated:
            flash(u"请重新登录", "info")
    else:
        flash(u"请先登录","info")
    if user:
        profile = Profile.query.filter_by(user_id=user.id).first()
        if profile:
            t = time.localtime(profile.birthday) if profile.birthday else None
            form = ProfileForm(
                english_first_name = profile.english_first_name,
                english_last_name = profile.english_last_name,
                birthday_year = t.tm_year if t else '',
                birthday_month = t.tm_mon if t else '',
                birthday_day = t.tm_mday if t else '',
                address = profile.address,
                phone = profile.phone,
                email=user.email)
        else:
            form = ProfileForm(email=user.email)
    else:
        form = ProfileForm()
    if form.validate_on_submit():
        if not profile:
            profile = Profile(user_id=user.id)
        form.populate_obj(profile)
        tstr = '%s-%s-%s' % (
            form.birthday_year.data, 
            form.birthday_month.data,
            form.birthday_day.data)
        profile.birthday = int(time.mktime(time.strptime(tstr,'%Y-%m-%d')))
        db.session.add(profile)
        db.session.commit()
        flash(u"您已成功提交申请", "success")

        source = request.values.get('source')
        auth_base64 = request.values.get('auth')

        return redirect(request.url)
    return render_template("account/setting_profile.html", form=form)
